package com.shire.shire_interface.common.utils;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * JSON 字符串和MAP（或数组）互转
 *
 */
public class JsonFormat {
    protected static final Logger logger = LoggerFactory.getLogger(JsonFormat.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String toJson(Object object){
        try{
            return objectMapper.writeValueAsString(object);
        }
        catch (Exception e){
            logger.error("Object转换json字符串异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T toObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        }
        catch (Exception e) {
            logger.error("Json字符串转换成对象异常：{}", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> toMap(String json){
        return toObject(json, Map.class);
    }

    public static CMap<String, Object> toCMap(String json){
        return toObject(json, CMap.class);
    }


}
